package com.mindata.blockchain.socket.handler.server.block;

import com.mindata.blockchain.ApplicationContextProvider;
import com.mindata.blockchain.block.block.Block;
import com.mindata.blockchain.block.check.CheckerManager;
import com.mindata.blockchain.socket.base.AbstractBlockHandler;
import com.mindata.blockchain.socket.body.rpc.RpcBlockBody;
import com.mindata.blockchain.socket.body.rpc.RpcCheckBlockBody;
import com.mindata.blockchain.socket.common.queue.GlobalBlockQueue;
import com.mindata.blockchain.socket.packet.BlockPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

/**
 * @author maltyshane
 */
public class GlobalHandler extends AbstractBlockHandler<RpcBlockBody> {
    GlobalBlockQueue globalBlockQueue = ApplicationContextProvider.getBean(GlobalBlockQueue.class);
    private Logger logger = LoggerFactory.getLogger(GlobalHandler.class);

    @Override
    public Class bodyClass() {
        return RpcBlockBody.class;
    }

    @Override
    public Object handler(BlockPacket packet, RpcBlockBody bsBody, ChannelContext channelContext) throws Exception {
        Block block = bsBody.getBlock();
        logger.info("收到来自于<{}><global共识的区块>消息，block信息为[{}]", bsBody.getAppId(), block.getHash());

        CheckerManager checkerManager = ApplicationContextProvider.getBean(CheckerManager.class);
        //对区块的基本信息进行校验，校验通过后进入DGL的globalBlockQueue队列
        RpcCheckBlockBody rpcCheckBlockBody = checkerManager.dglcheck(block);
//        logger.info("校验结果:{}", rpcCheckBlockBody);
        if (rpcCheckBlockBody.getCode() == 0) {
            // 添加到Queue中
            globalBlockQueue.push(block);
        }
        return null;
    }
}
